<template>
  <div class="container">

    <el-card :style="{maxHeight: contentHeight * 0.8 + 'px'}" class="box-card">
      <div class="title">储值卡充值</div>
      <div class="card-form">
        <el-steps :active="1" finish-status="success" simple style="margin-bottom: 20px;">
          <el-step title="识别卡号"></el-step>
          <el-step title="填写金额"></el-step>
          <el-step title="确认充值"></el-step>
        </el-steps>
        <el-form ref="dataFormRef" :model="dataForm" :rules="formRules" label-width="120px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="卡编号：" prop="cardNo">
                <el-input v-model="dataForm.cardNo" readonly></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="卡余额：" prop="balance">
                <el-input v-model="dataForm.balance" readonly></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="充值金额：" prop="amount">
                <el-input ref="amountRef" v-model="dataForm.amount" clearable type="number"></el-input>
                <el-tag v-for="item in amountList" :key="item" effect="dark" size="small"
                        style="margin-right: 5px;cursor: pointer;" type="warning" @click="setAmount(item)">{{ item }}
                </el-tag>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="支付方式：">
                <div class="payway" @click="handlePaywayClick('wechat')">
                  <div class="icon">
                    <img alt="" src="@/assets/icons/wepay.svg">
                  </div>
                  <div class="name">微信</div>
                </div>
                <div class="payway" @click="handlePaywayClick('alipay')">
                  <div class="icon">
                    <img alt="" src="@/assets/icons/alipay.svg">
                  </div>
                  <div class="name">支付宝</div>
                </div>
                <div class="payway" @click="handlePaywayClick('yinlian')">
                  <div class="icon">
                    <img alt="" src="@/assets/icons/yinlian.svg">
                  </div>
                  <div class="name">银联卡</div>
                </div>
                <div class="payway" @click="handlePaywayClick('cash')">
                  <div class="icon">
                    <img alt="" src="@/assets/icons/cash.svg">
                  </div>
                  <div class="name">现金</div>
                </div>
                <div class="payway" @click="handlePaywayClick('changeCard')">
                  <div class="icon">
                    <img alt="" src="@/assets/icons/exchange.svg">
                  </div>
                  <div class="name">换卡充值</div>
                </div>
                <div class="payway" @click="handlePaywayClick('bankTransfer')">
                  <div class="icon">
                    <img alt="" src="@/assets/icons/bankTransfer.svg">
                  </div>
                  <div class="name">银行转账</div>
                </div>

              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <!-- 工具栏 -->
        <div class="btn-bar">
          <el-button round size="small" type="primary" @click="enterCardNo">手输卡号</el-button>
          <el-button round size="small" type="warning" @click="readCard">重新识别</el-button>
          <el-button round size="small" type="danger" @click="resetForm">重置表单</el-button>
        </div>
      </div>
    </el-card>
    <div class="home-btn">
      <div class="btn-item">
        <el-button icon="el-icon-back" round size="small" type="primary" @click="goBackHome"> 返 回</el-button>
      </div>
      <div class="btn-item">
        <el-button icon="el-icon-search" round size="small" type="info" @click="goCardInfo">卡查询</el-button>
      </div>
    </div>
  </div>
</template>

<script>

import {mapGetters} from 'vuex'
import {getCardInfo} from '@/api/card'
import {cartSettle, queryPayResult} from '@/api/settle'
import {rsaEncrypt} from '@/utils/rsa'
import {readCardNo} from '@/utils/cardreader'
import {PAY_WAY_NAME_MAP} from '@/utils/common'

export default {
  name: 'CardRecharge',
  data () {
    return {
      readCardInterval: null,
      amountList: [200, 500, 1000, 2000, 5000],
      dataForm: {
        cardNo: '',
        balance: '',
        amount: '',
        payType: '',
        masterUid: '',
        stationId: '' // 开卡油站
      },
      formRules: {
        cardNo: {required: true, message: '卡号不能为空！', trigger: 'change'},
        amount: {required: true, message: '充值金额不能为空！', trigger: 'change'}
      }
    }
  },
  computed: {
    ...mapGetters(['contentHeight', 'operator', 'stationId', 'stationName', 'shiftName'])
  },
  mounted () {
    this.readCardInterval = setInterval(() => {
      this.readCard()
    }, 1000)
  },
  methods: {
    goBackHome () {
      this.$router.push('/card')
    },
    goCardInfo () {
      this.$router.push('/card/info')
    },
    readCard () {
      var cardNo = readCardNo()
      if (cardNo) {
        this.dataForm.cardNo = cardNo
        this.getCardInfoByCardNo(cardNo)
        window.clearInterval(this.readCardInterval)
      }
    },
    resetForm () {
      this.$refs['dataFormRef'].resetFields()
      console.log(this.dataForm)
    },
    enterCardNo () {
      this.$prompt('请输入储值卡号码', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputType: 'text',
        inputErrorMessage: '储值卡号码格式不正确'
      }).then(({value}) => {
        console.log(value)
        if (value) {
          this.dataForm.cardNo = value
          this.getCardInfoByCardNo(value)
        }
      }).catch(() => {
        console.log('cancel')
      })
    },
    getCardInfoByCardNo (cardNo) {
      getCardInfo(cardNo).then(res => {
        // 判断是否为主卡，副卡不允许充值
        if (res.data.masterUid) {
          this.resetForm()
          this.$message.warning('副卡不允许充值！')
          return false
        }
        if (res.data.cardType === 5) {
          this.resetForm()
          this.$message.warning('不记名优惠卡不允许充值！')
          return false
        }
        console.log('cardInfo')
        console.log(res)
        this.dataForm.balance = res.data.balance
        this.dataForm.masterUid = res.data.masterUid
        this.dataForm.stationId = res.data.stationId
        this.dataForm.amount = ''
        this.$message.success('查询成功！')
        this.$refs['amountRef'].focus()
      }).catch(err => {
        console.log(err)
        this.resetForm()
        this.$message.warning(err || '系统不存在该卡号')
      })
    },
    handlePaywayClick (payway) {
      console.log('handlePaywayClick')
      console.log(payway)
      this.dataForm.payType = payway
      // if (this.stationId !== this.dataForm.stationId) {
      //   this.$message.error('该储值卡不能在该站充值')
      //   return false
      // }
      this.$refs['dataFormRef'].validate((valid) => {
        if (valid) {
          if (this.dataForm.amount < 0.01) {
            this.$message.error('充值金额必须大于0.01元')
            return false
          }
          if (payway === 'wechat' || payway === 'alipay') {
            // 弹出支付码输入窗口
            this.$prompt('请扫描顾客支付码', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              inputType: 'password',
              closeOnClickModal: false,
              inputErrorMessage: '支付码不正确'
            }).then(({value}) => {
              console.log(value)
              this.doCartSettle(payway, value)
            }).catch(() => {
              console.log('取消扫码')
            })
          } else {
            // 弹窗确认一下是否执行支付
            this.$confirm('是否确认【' + PAY_WAY_NAME_MAP[payway] + '】充值 ' + this.dataForm.amount + ' 元？', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.doCartSettle(payway, '')
            }).catch(() => {
            })
          }
        }
      })
    },
    setAmount (amount) {
      this.dataForm.amount = amount
    },
    // 执行购物车结算
    doCartSettle (payWay, paymentCode) {
      var cartItem = {
        id: '',
        name: this.dataForm.cardNo,
        nums: 1,
        type: 'recharge',
        price: this.dataForm.amount,
        amount: this.dataForm.amount,
        data: {
          cardNo: this.dataForm.cardNo,
          amount: this.dataForm.amount,
          payAmount: this.dataForm.amount
        }
      }
      var cart = {
        operateTime: new Date(),
        cartList: [cartItem],
        stationId: this.stationId, // 油站ID
        memberId: '', // 会员ID
        operator: this.operator, // 操作员
        paymentType: payWay, // 支付方式
        paymentCode: paymentCode ? rsaEncrypt(paymentCode) : '', // 支付码（RSA加密后）
        cardUid: '', // 储值卡UID
        amount: this.dataForm.amount, // 应付金额
        payAmount: this.dataForm.amount, // 支付金额
        oilCouponAmount: 0.00,
        oilCouponIds: '',
        oilPayAmount: 0.00,
        oilAmount: 0.00,
        goodsAmount: 0.00,
        goodsPayAmount: 0.00,
        goodsCouponIds: '',
        goodsCouponAmount: 0.00
      }
      console.log(cart)
      cartSettle(cart).then((res) => {
        console.log(res)
        if (res.data && res.data.status === 'done') {
          this.$message.success('充值成功！')
          // this.printRechargeReceipt()
          this.getCardInfoByCardNo(this.dataForm.cardNo)
        } else if (res.data && res.data.status === 'doing') {
          console.log(res.data)
          console.log(res.data.paymentNo)
          console.log('需要定时查询支付结果')
          this.getCartSettleResult(res.data.paymentNo)
        }
      }).catch((err) => {
        console.log(err)
        this.$message.error(err || '请求出错')
      })
    },
    // 定时获取支付结果
    getCartSettleResult (paymentNo) {
      this.queryTimes = 0
      this.queryLoading = this.$loading({text: '结果查询中...'})
      this.queryInterval = setInterval(() => {
        if (this.queryTimes > 200) {
          // 查询次数到达上限，提示支付超时，停止定时查询
          this.$message.warning('支付结果查询超时')
          window.clearInterval(this.queryInterval)
          return false
        }
        this.queryTimes = this.queryTimes + 1
        queryPayResult({stationId: this.stationId, paymentNo: paymentNo}).then(res => {
          console.log('queryPayResult:' + paymentNo + ':' + res.data.status)
          if (res.data && res.data.status === 'done') {
            window.clearInterval(this.queryInterval)
            this.queryLoading.close()
            // 支付成功
            this.$message.success('充值成功！')
            this.getCardInfoByCardNo(this.dataForm.cardNo)
          } else if (res.data && res.data.status === 'error') {
            this.queryLoading.close()
            // 支付失败
            window.clearInterval(this.queryInterval)
            this.$alert(res.data.message || '支付失败！', '支付失败', {type: 'error'})
          }
        }).catch(err => {
          console.log(err)
        })
      }, 1000)
    }
  },
  beforeDestroy () {
    window.clearInterval(this.readCardInterval)
  }
}
</script>

<style scoped>
.el-select {
  width: 100%;
}

.box-card {
  width: 60%;
  margin-left: 20%;
  position: absolute;
  top: 4%;
  overflow-y: auto;
}

.home-btn {
  position: absolute;
  top: 2%;
  left: 2%;
}

.btn-item {
  margin-bottom: 20px;
}

.title {
  text-align: center;
  padding-top: 1%;
  font-size: 1.6rem;
  color: #666;
}

.card-form {
  background: white;
  padding: 20px;
}

.btn-bar {
  text-align: right;
}

.payway {
  display: inline-block;
  width: 50px;
  height: 50px;
  text-align: center;
  border-radius: 8px;
  background: #ecf5ff;
  padding: 5px;
  cursor: pointer;
  margin-right: 10px;
}

.payway .icon {
  height: 30px;
}

.payway .name {
  padding-top: 10px;
  line-height: 10px;
  font-size: 12px;
}

.payway .icon img {
  height: 30px;
  width: 50px;
}
</style>
